package com.bz.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

@Configuration
public class CleanupConfig {

    private static final Logger logger = LoggerFactory.getLogger(CleanupConfig.class);

    @Bean
    public CommandLineRunner cleanupTempFiles() {
        return args -> {
            File tempDir = new File(System.getProperty("java.io.tmpdir"));
            File[] files = tempDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().startsWith("tomcat.")) {
                        logger.info("删除目录: {}", file.getAbsolutePath());
                        deleteDirectory(file);
                    }
                }
            }
        };
    }

    private void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    logger.debug("删除文件: {}", file.getAbsolutePath());
                    file.delete();
                }
            }
        }
        logger.debug("删除目录: {}", directory.getAbsolutePath());
        directory.delete();
    }
}
